<template>
  <div>
    <div>
      <div style="margin-right: 20px" class="center">
        <el-avatar class="header-img" :size="40" :src="user.avatar" style="margin-right: 20px"></el-avatar>
        <el-input placeholder="输入评论..." v-model="content" style="width: 75%; margin-right: 20px"></el-input>
        <el-button class="reply-btn" size="medium" @click="postComment" type="primary">发表评论</el-button>
      </div>
      <div style="line-height: 36px">
        <span>共{{ this.blogDetail.commentsNum }}条评论</span>
      </div>
    </div>

    <div style="padding-top: 20px">
      <div v-for="(comment,index) in comments" v-bind:key="index">
        <div style="float: left" class="user-face">
          <el-avatar class="header-img" :size="40" :src="comment.avatar"></el-avatar>
        </div>
        <div style="margin-left: 60px" class="con">
          <div class="user-name">
            <span style="font-weight: bold; margin-right: 20px;">{{ comment.username }}</span>
          </div>
          <p class="context">{{ comment.content }}</p>
          <div>
            <span class="info">{{ comment.publishTime }}</span>
            <el-button type="text" class="info" @click="showReplayInput(comment.cid)">回复</el-button>
          </div>
          <div style="margin-right: 20px" v-if="commentIndex===comment.cid" class="center">
            <el-avatar class="header-img" :size="40" :src="user.avatar" style="margin-right: 20px"></el-avatar>
            <el-input :placeholder="'回复 @'+comment.username" v-model="replayContent"
                      style="width: 75%; margin-right: 20px"></el-input>
            <el-button class="reply-btn" size="medium"
                       @click="replayComment(comment.username,comment.cid,comment.level)" type="primary">发表评论
            </el-button>
          </div>
          <ChildComment :children="comment.children"></ChildComment>
        </div>

      </div>
    </div>
  </div>
</template>

<script>
import qs from 'qs'
import ChildComment from "./ChildComment";

export default {
  inject: ['reload'],
  name: "Comment",
  components: {
    ChildComment,
  },
  data() {
    return {
      comments: [],
      user: this.$store.state.user,
      blogDetail: this.$store.state.blogDetail,
      content: '',
      replayContent: '',
      commentIndex: this.$store.state.replayId,
      replayUsername: '',
    }
  },
  methods: {
    getUserData() {
      localStorage.getItem("user")
    },
    postComment() {
      if (this.user.username === '') {
        this.$message.error("请先登录再发表评论");
      } else {
        if (this.content !== '') {
          let comment = {
            bid: this.blogDetail.bid,
            content: this.content,
            username: this.user.username,
          }
          this.axios.post("/blog/insertComment", comment).then((response) => {
            //sessionStorage.setItem("blogDetail",JSON.stringify(this.$store.state.blogDetail));
            this.reload();
          })
        } else {
          this.$message.error("评论内容为空");
        }
      }
    },
    replayComment(pusername, pid, level) {
      if (this.user.username === '') {
        this.$message.error("请先登录再发表评论");
      } else {
        if (this.replayContent !== '') {
          let comment = {
            bid: this.blogDetail.bid,
            pid: pid,
            username: this.user.username,
            pusername: pusername,
            level: level,
            content: this.replayContent,
          };
          this.axios.post("/blog/insertComment", comment).then((response) => {
            this.reload();
          })
        } else {
          this.$message.error("评论内容为空");
        }
      }
    },
    getComment() {
      this.axios.post('/blog/queryComment', qs.stringify({
        bid: this.blogDetail.bid
      })).then((response) => {
        this.recursion(response.data, this.comments);

        this.comments = this.listToTree(this.comments);
      })
    },
    recursion(node, arr) {
      node.forEach(data => {
        let comment = {
          bid: this.blogDetail.bid,
          avatar: '',
          username: '',
          pusername: '',
          content: '',
          publishTime: '',
          cid: '',
          pid: '',
          likeNum: 0,
          level:1,
          children: [],
        }
        comment.bid = data.bid;
        comment.username = data.username;
        comment.pusername = data.pusername;
        comment.content = data.content;
        comment.cid = data.cid;
        comment.pid = data.pid;
        comment.level = data.level;
        comment.likeNum = data.likeNum;
        let date = this.getNowTime(data.publishTime);
        comment.publishTime = date;
        this.axios.post('/user/queryUserByName', qs.stringify({
          username: data.username
        })).then((res) => {
          comment.avatar = res.data.avatar;
        });
        comment.children = data.children;

        arr.push(comment);
        data.children && this.recursion(data.children, arr);
      })
    },
    listToTree(list) {
      let info = list.reduce((map, node) => (map[node.cid] = node, node.children = [], map), {})
      return list.filter(node => {
        info[node.pid] && info[node.pid].children.push(node)
        return !node.pid
      })
    },
    getNowTime(date) {
      date = date.replace(/-/g, "/");
      let start = new Date(date);
      let end = new Date();
      let diff = (end.getTime() - start.getTime()) / 1000;
      if (diff <= 10) {
        date = "刚刚";
      } else if (diff < 60 && diff > 10) {
        date = Math.ceil(diff / 10) * 10 + "秒前";
        //console.log(Math.floor(diff/10)*10+"秒前");
      } else if (Math.ceil(diff / 60) < 60) {
        date = Math.ceil(diff / 60) + "分钟前";
        //console.log(Math.ceil(diff/60)+"分钟前");
      } else if (Math.ceil(diff / 3600) < 24) {
        date = Math.ceil(diff / 3600) + "小时前";
        //console.log(Math.ceil(diff/3600)+"小时前")
      } else {
        date = date.replace(/\//g, "-")
        let temp = date.split(":");
        date = temp[0] + ":" + temp[1];
        //console.log(date);
      }
      return date;
    },
    showReplayInput(id) {
      this.$store.commit("setReplayId", id);
    }
  },
  watch: {
    "$store.state.user"() {
      this.user = this.$store.getters.getUser;
    },
    "$store.state.blogDetail"() {
      this.blogDetail = this.$store.getters.getBlogDetail;
      this.getComment();
    },
    "$store.state.replayId"() {
      this.commentIndex = this.$store.getters.getReplayId;
    }
  },
  created() {
    if (localStorage.getItem("user") != null) {
      this.user = JSON.parse(localStorage.getItem("user"));
    }
    if (sessionStorage.getItem("blogDetail") != null) {
      this.blogDetail = JSON.parse(sessionStorage.getItem("blogDetail"));
      this.$store.commit("setBlog", this.blogDetail);
    }
  },
  mounted() {

  }
}
</script>

<style scoped>
.center {
  display: flex;
  align-items: center;
  margin-bottom: 20px
}

.user-face {
  float: left;
  margin: 24px 0 0 5px;
  position: relative;
}

.con {
  position: relative;
  margin-left: 85px;
  padding: 22px 0 14px 0;
  border-top: 1px solid #e5e9ef;
}

.user-name {
  padding: 0 0 4px;
}

.context {
  line-height: 20px;
  padding: 2px 0;
  font-size: 14px;
  text-shadow: none;
  overflow: hidden;
  margin: 0;
}

.info {
  margin-right: 20px;
  font-size: 12px;
  color: gray
}

.el-button.info:hover {
  color: deepskyblue;
}
</style>
